﻿// The Html element contains a literal HTML content
define([
    'Wjs/ui/elements/Element',
    'Wjs/ui/elements/mixins/Loadable'
],
function () {
    'use strict';

    return Wjs.defineOnce({

        type: 'Html',

        internal: {

            base: Wjs.getType('Element'),

            mixins: [
                Wjs.getType('Loadable')
            ]
        },

        setDomContent: function (content) {
            var parent = this.parent,
                parentDomEl = parent.domEl;

            parentDomEl.innerHTML = content; //TODO Verify the HTML contains a single parent node

            //if (parentDomEl.children.length > 1) { // It can be zero for an empty HTML content
            //    throw 'The html element only supports a single node as root element';
            //}

            this.domEl = parentDomEl.firstChild;
        },

        createDomElement: function () {

            this.setDomContent(this.html);

            this.html = null; // Not needed after rendered
        },

        getHtml: function () {

            if (this.isRendered()) {

                return this.parent.domEl.innerHTML;
            }
            else { // Not rendered

                return this.html;
            }
        },

        setHtml: function (html) {

            if (!this.isRendered()) {

                this.html = html;
            }
            else {

                this.setDomContent(html)
            }

            return this;
        },

        getContent: function () {

            return this.getHtml();
        },

        // Called by the loader when the data is loaded
        loadHandler: function (data, contentType) {

            data = this.draw ? this.draw(data) : data;

            this.setHtml(data);
        },

        // Creates a copy of this element
        clone: function () {
            var cloned = Wjs.new(this.type);

            cloned.setHtml(this.getHtml());

            return cloned;
        }
    });

});